using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;

namespace ClientTools.Client.Controls.Logging
{
    public partial class ucLogs : BaseUserControl, IUserControl
    {
        #region Private variables
        private Library.Interfaces.ILogging _ActLogging;
        #endregion

        public ucLogs()
        {
            InitializeComponent();
        }

        private void tsbResetFilter_Click(object sender, EventArgs e)
        {
            this.ResetFilter();
        }

        private void tsbDeleteLog_Click(object sender, EventArgs e)
        {
            this.Cursor = Cursors.WaitCursor;
            int[] delvals = new int[this.dgLogs.SelectedRows.Count];

            for (int i = 0; i < this.dgLogs.SelectedRows.Count; i++)
            {
                delvals[i] = (int)this.dgLogs.SelectedRows[i].Cells["ID"].Value;
            }

            this._ActLogging.DeleteLogsByIDs(delvals);
            this.GetLogs();
            this.Cursor = Cursors.Default;
        }

        #region GetLogs
        private void GetLogs()
        {
            this.Cursor = Cursors.WaitCursor;

            System.Nullable<int> maxrow = null;
            System.Nullable<DateTime> startdate = null;
            System.Nullable<DateTime> enddate = null;
            string header = null;
            System.Nullable<int> userid = null;
            System.Nullable<int> nodeid = null;
            string comment = null;

            maxrow = Decimal.ToInt32(this.nudMaxRows.Value);

            if (this.txtNodeID.Text.Trim() != "")
            {
                int x;
                if (int.TryParse(this.txtNodeID.Text.Trim(), out x))
                {
                    nodeid = int.Parse(this.txtNodeID.Text.Trim());
                }
                else
                {
                    MessageBox.Show("NodeID is not a number!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
            }

            if (this.txtUserID.Text.Trim() != "")
            {
                int x;
                if (int.TryParse(this.txtUserID.Text.Trim(), out x))
                {
                    userid = int.Parse(this.txtUserID.Text.Trim());
                }
                else
                {
                    MessageBox.Show("UserID is not a number!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
            }
            if (this.cboHeader.SelectedIndex != -1 && this.cboHeader.SelectedIndex != 0)
            {
                header = this.cboHeader.SelectedItem.ToString();
            }

            if (this.dtpStartdate.Checked)
            {
                startdate = this.dtpStartdate.Value;
            }

            if (this.dtpEnddate.Checked)
            {
                enddate = this.dtpEnddate.Value;
            }

            if (this.txtComment.Text.Trim() != "")
            {
                comment = this.txtComment.Text.Trim();
            }
            global::ClientTools.Library.Logging.LogCollection logs;
            try
            {
                logs = this._ActLogging.GetLogs(startdate, enddate, header, userid, nodeid, maxrow, comment);
            }
            catch (Exception ex)
            {
                this.ClearData();
                this.Enabled = false;
                this.Cursor = Cursors.Default;
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            this.dgLogs.DataSource = logs;
            this.dgLogs.Enabled = true;
            GridViewHelper.SetDisplayColums(this.dgLogs, "NodeID;UserID;DateStamp;LogHeader;LogComment", true);
            this.dgLogs.Columns["Datestamp"].DefaultCellStyle.Format = "yyyy-MM-dd HH:mm:ss";
            this.lblCount.Text = logs.Count.ToString();

            this.Cursor = Cursors.Default;

        }

        private void tsbGetLogs_Click(object sender, EventArgs e)
        {
            this.GetLogs();
        }

        private void nudMaxRows_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                this.GetLogs();
            }
        }

        private void txtUserID_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                this.GetLogs();
            }
        }

        private void txtNodeID_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                this.GetLogs();
            }
        }

        private void cboHeader_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.GetLogs();
        }

        private void txtComment_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                this.GetLogs();
            }
        }
        #endregion

        #region I_UserControl Member

        public void SetData(global::ClientTools.Client.Library.Settings.Profile profile)
        {
            this.ActProfile = profile;
            this.ActProfile.InitProvider();
            this.ActProvider = this.ActProfile.ProviderObject;

            if (!this.ImplementsLogging())
            {
                this.Enabled = false;
                return;
            }

            this._ActLogging = (Library.Interfaces.ILogging)this.ActProvider;
            this.ClearData();
            this.Enabled = true;
            this.GetLogHeaders();
        }

        public string Header
        {
            get { return "Logging"; }
        }

        public int Sort
        {
            get { return 1; }
        }

        public bool ShowDelimiter
        {
            get { return true; }
        }

        public Image ButtonImage
        {
            get { return this.tsbLogViewer.Image; }
        }

        public string ButtonText
        {
            get { return "LogViewer"; }
        }

        #endregion

        public void ClearData()
        {
            this.dgLogs.DataSource = null;
            this.dgLogs.Enabled = false;
        }

        private void GetLogHeaders()
        {
            this.Cursor = Cursors.WaitCursor;
            global::ClientTools.Library.Logging.LogInfoCollection loginfos;
            try
            {
                loginfos = this._ActLogging.GetLogInfos();
            }
            catch (Exception ex)
            {
                this.ClearData();
                this.Enabled = false;
                this.Cursor = Cursors.Default;
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            this.cboHeader.Items.Clear();
            if (loginfos != null)
            {
                this.cboHeader.Items.Add(">> Select a header <<");
                foreach (global::ClientTools.Library.Logging.LogInfo li in loginfos)
                {
                    this.cboHeader.Items.Add(li.LogHeader);
                }
                this.cboHeader.SelectedIndex = 0;
            }
            this.Cursor = Cursors.Default;
        }

        private void ucLogs_Load(object sender, EventArgs e)
        {
            GridViewHelper.SetGridLayout(this.dgLogs);
        }

        private void ResetFilter()
        {
            this.txtNodeID.Text = "";
            this.txtUserID.Text = "";
            this.cboHeader.SelectedIndex = 0;

            this.nudMaxRows.Value = 100;

            this.dtpEnddate.Value = DateTime.Now;
            this.dtpStartdate.Value = DateTime.Now;
            this.dtpEnddate.Checked = false;
            this.dtpStartdate.Checked = false;
        }

        private void cmdClearLogsByDate_Click(object sender, EventArgs e)
        {
            this.Cursor = Cursors.WaitCursor;
            this._ActLogging.DeleteLogsByDate(this.DateTimePicker1.Value);
            this.GetLogInfos();
            this.Cursor = Cursors.Default;
        }

        private void cmdClearLogsByHeader_Click(object sender, EventArgs e)
        {
            if (this.cboHeader.SelectedItem == null)
            {
                MessageBox.Show("No header selected!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            this.Cursor = Cursors.WaitCursor;
            try
            {
                this._ActLogging.DeleteLogsByHeader((string)this.cboHeader.SelectedItem);
            }
            catch (Exception ex)
            {
                this.ClearData();
                this.Enabled = false;
                this.Cursor = Cursors.Default;
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            this.GetLogInfos();
            this.Cursor = Cursors.Default;
        }

        private void GetLogInfos()
        {
            global::ClientTools.Library.Logging.LogInfoCollection loginfos;
            try
            {
                loginfos = this._ActLogging.GetLogInfos();
            }
            catch (Exception ex)
            {
                this.ClearData();
                this.Enabled = false;
                this.Cursor = Cursors.Default;
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            this.comboBox1.Items.Clear();
            this.lvLogInfos.Items.Clear();
            if (loginfos != null)
            {
                foreach (global::ClientTools.Library.Logging.LogInfo li in loginfos)
                {
                    this.comboBox1.Items.Add(li.LogHeader);
                    ListViewItem lv = new ListViewItem(li.LogHeader + " (" + li.Count.ToString() + ")");
                    this.lvLogInfos.Items.Add(lv.Text);
                    lv.Tag = li;
                }
                this.pnlContent.Enabled = true;
                this.lblSum.Text = "Sum: " + loginfos.Count.ToString();
                this.cboHeader.SelectedIndex = 0;
            }

        }

        private void tsbGetLogInfos_Click(object sender, EventArgs e)
        {
            this.Cursor = Cursors.WaitCursor;
            this.GetLogInfos();
            this.Cursor = Cursors.Default;
        }

        private void contextMenuStrip1_Opening(object sender, CancelEventArgs e)
        {
            if (this.dgLogs.Rows.Count == 0 || this.dgLogs.SelectedRows.Count != 1)
            {
                e.Cancel = true;
                return;
            }
        }

        private void copyCommentToClipboardToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Clipboard.SetText((string)dgLogs.SelectedRows[0].Cells["LogComment"].Value);
        }

    }
}
